﻿using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Collections.Generic;
using MVCQuick.Framework;
using MVCQuick.Framework.Repository;

namespace MvcMusicStore.Models
{
    public class AlbumEditModel
    {
        [ScaffoldColumn(false)]
        public int Id { get; set; }

        [DisplayName("Genre")]
        public int GenreId { get; set; }

        [DisplayName("Artist")]
        public int ArtistId { get; set; }

        [Required(ErrorMessage = "An Album Title is required")]
        [StringLength(160)]
        public string Title { get; set; }

        [Required(ErrorMessage = "Price is required")]
        [Range(0.01, 100.00,
            ErrorMessage = "Price must be between 0.01 and 100.00")]
        public decimal Price { get; set; }

        [DisplayName("Album Art URL")]
        [StringLength(1024)]
        public string AlbumArtUrl { get; set; }


        public static AlbumEditModel Get(IRepository repository, int id)
        {
            AlbumEditModel model = new AlbumEditModel();

            Album album = repository.Get<Album>(id);

            if (album != null)
            {
                model.Id = album.Id;
                model.GenreId = (album.Genre != null ? album.Genre.Id : 0);
                model.ArtistId = (album.Artist != null ? album.Artist.Id : 0);
                model.Title = album.Title;
                model.Price = album.Price;
                model.AlbumArtUrl = album.AlbumArtUrl;
            }


            return model;
        }

        public static void Create(IRepository repository, AlbumEditModel model)
        {    
            Album album = new Album();
            album.Title = model.Title;
            album.Price = model.Price;
            album.AlbumArtUrl = model.AlbumArtUrl;
            album.Genre = repository.Get<Genre>(model.GenreId);
            album.Artist = repository.Get<Artist>(model.ArtistId);

            repository.Save(album);
        }

        public static void Update(IRepository repository, AlbumEditModel model)
        {
            Album album = repository.Get<Album>(model.Id);
            album.Title = model.Title;
            album.Price = model.Price;
            album.AlbumArtUrl = model.AlbumArtUrl;
            album.Genre = repository.Get<Genre>(model.GenreId);
            album.Artist = repository.Get<Artist>(model.ArtistId);

            repository.Update(album);
        }


        public static void Delete(IRepository repository, int id)
        {
            Album album = repository.Get<Album>(id);

            repository.Delete(album);
        }

    }
}